using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace UploadFileDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class UploadController : ControllerBase
    {
        const string DataFileName = "DataFile.json";
        [HttpPost]
        public async Task<IActionResult> UploadAsync(IFormFile file)
        {
            if (file.Length <= 0) return Ok();
            string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadFiles");
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            Guid id = Guid.NewGuid();
            string filePath = Path.Combine(directoryPath, file.FileName);
            if (System.IO.File.Exists(filePath)) return Ok(new { error = "文件已存在" });
            using (FileStream stream = System.IO.File.Create(filePath))
            {
                await file.CopyToAsync(stream);
            }
            string dataFilePath = Path.Combine(directoryPath, DataFileName);
            if (System.IO.File.Exists(dataFilePath))
            {
                string json = await System.IO.File.ReadAllTextAsync(dataFilePath);
                Dictionary<string, string> data = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? [];
                data[id.ToString()] = file.FileName;
                json = JsonSerializer.Serialize(data);
                await System.IO.File.WriteAllTextAsync(dataFilePath, json);
            }
            else
            {
                Dictionary<string, string> data = new() { { id.ToString(), file.FileName } };
                string json = JsonSerializer.Serialize(data);
                await System.IO.File.WriteAllTextAsync(dataFilePath, json);
            }
            return Ok(new { ID = id });
        }

        [HttpGet]
        public async Task<IActionResult> DownloadAsync(Guid id)
        {
            string directoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadFiles");
            string dataFilePath = Path.Combine(directoryPath, DataFileName);
            if (!System.IO.File.Exists(dataFilePath)) return Ok();
            string json = await System.IO.File.ReadAllTextAsync(dataFilePath);
            Dictionary<string, string> data = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? [];
            string fileName = data[id.ToString()];
            string filePath = Path.Combine(directoryPath, fileName);
            if (!System.IO.File.Exists(filePath)) return Ok();
            return File(System.IO.File.OpenRead(filePath), "application/octet-stream", fileName);
        }
    }
}
